import cv2
import numpy as np


def rgb(img):
    # 图像处理
    rgb = cv2.cvtColor(img, cv2.COLOR_BGR2YCR_CB)
    cv2.imshow("rgb",rgb)
    (y, cr, cb) = cv2.split(rgb)
    print(cr.shape)
    colorInset = np.zeros((cr.shape), dtype=np.uint8)    # 表示这是颜色区间
    cv2.imshow("inset",colorInset)
    # 参数（图像，中心位置，轴线，角度，开始角度，结束角度，颜色，厚度）
    cv2.ellipse(colorInset, (113, 155), (23, 15), 43, 0, 360, (255, 255, 255), -1)
    # 画了一片黑
    skin = np.zeros(cr.shape, dtype=np.uint8)
    (x, y) = cr.shape
    for i in range(0, x):
        for j in range(0, y):
            CR = rgb[i, j, 1]
            CB = rgb[i, j, 2]
            if colorInset[CR, CB] > 0:
                skin[i, j] = 255
    cv2.imshow('mask', skin)
    dst = cv2.bitwise_and(img, img, mask=skin)
    v1 = np.hstack((img, dst))
    cv2.imshow("all", v1)


def hsv(imgout):
    hsv = cv2.cvtColor(imgOut, cv2.COLOR_BGR2HSV)
    cv2.imshow("hsv",hsv)
    lower = np.array([0,2,130])
    upper = np.array([179,200,254])
    # 蒙版
    mask = cv2.inRange(hsv, lower, upper)
    dst = cv2.bitwise_and(imgOut, imgOut, mask=mask)
    cv2.imshow("hsvmask", mask)
    v1 = np.hstack((imgOut, dst))
    cv2.imshow("hsvall", v1)
    cv2.waitKey()


def getface(img):
    faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_alt2.xml")
    imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(imgGray,1.1,4)
    width = 300
    imgOut = img
    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
        # ******************************提取人脸部分，并且进行颜色识别，肤色
        pts1 = np.float32([[x, y], [x + w, y], [x, y + h], [x + w, y + h]])
        height = int(h / w * width)
        pts2 = np.float32([[0, 0], [width, 0], [0, height], [width, height]])
        matrix = cv2.getPerspectiveTransform(pts1, pts2)
        imgOut = cv2.warpPerspective(img, matrix, (width, height))
        # ******************************提取人脸部分，并且进行颜色识别，肤色
    return imgOut


if __name__ == '__main__':
    for i in range(1,11):
        src = 'people/'+str(i)+'.png'
        img = cv2.imread(src)
        imgOut = getface(img)
        rgb(imgOut)
        hsv(imgOut)
        while True:
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break